package com.starsoft.frame.core.web;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.StringUtil;

public class DateStringConverter implements GenericConverter {

	@Override
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
		if (StringUtil.isEmpty(source)) {
			return null;
		}
		
		Object result = null;
		if(targetType.getType().equals(String.class)){
			if(sourceType.getType().equals(Date.class)){
				result = ((Date)source).getTime()+"";
			}else {
				result = ((Timestamp)source).getTime()+"";
			}
		} else {
			String sourceStr = (String)source;
			Date date = null;
			if(sourceStr.contains(":")){
				String format = "yyy-MM-dd HH:mm:ss";
				date = DateUtil.toDate(sourceStr, format);
			} else if(sourceStr.contains("-")){
				String format = "yyy-MM-dd";
				date = DateUtil.toDate(sourceStr, format);
			} else {
				long time = Long.parseLong((String)source);
				date = new Date(time);
			}
			result = date;
			if(targetType.getType().equals(Timestamp.class)){
				result = new Timestamp(date.getTime());
			}
		}
		return result;
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		Set<ConvertiblePair> pairs = new HashSet<ConvertiblePair>();
		pairs.add(new ConvertiblePair(String.class, Date.class));
		pairs.add(new ConvertiblePair(String.class, Timestamp.class));
		pairs.add(new ConvertiblePair(Date.class, String.class));
		pairs.add(new ConvertiblePair(Timestamp.class, String.class));
		return pairs;
	}

}
